import React, { useEffect, useState, useRef } from 'react'
import { useModel, history } from '@umijs/max'
import { ProTable } from '@ant-design/pro-components'
import { Button, InputNumber, App, Space, Badge, Table, Alert } from 'antd'
import { TransactionOutlined } from '@ant-design/icons'
import WithdrawalRecordDetails from './WithdrawalRecordDetails'
import './WithdrawalRecord.less'

// 状态对应
let STATUS_OBJ = {
  '-1': {
    status: '拒绝提现',
    statusType: 'error',
    btnColor: '#171717',
    btnText: '查看详情',
    detailsTitle: '查看详情'
  },
  1: {
    status: '待处理',
    statusType: 'warning'
  },
  2: {
    status: '待处理',
    statusType: 'warning'
  },
  3: {
    status: '已完成',
    statusType: 'success',
    btnColor: '#171717',
    btnText: '查看详情',
    detailsTitle: '查看详情'
  },
  4: {
    status: '已取消',
    statusType: 'default'
  }
}

const methodList = new Map([
  [2, '支付宝'],
  [3, '微信'],
  [1, '银行卡']
])

export default () => {
  const { GetPartnerWithdrawList } = useModel('Agent')
  const { message, modal } = App.useApp()

  const [pageSize, setPageSize] = useState(10) //  每页数量
  const [currentPage, setCurrentPage] = useState(1) //  当前页码
  const tableRef = useRef()

  // 尾部金额统计
  const [amountList, setAmountList] = useState({})

  // tab 选项卡
  const [tabActiveKey, setTabActiveKey] = useState('0')
  const [tabList, setTabList] = useState([
    {
      key: '0',
      tab: '全部',
      type: 'sum'
    },
    {
      key: '1',
      tab: '待处理',
      type: 'wait_deal_count'
    },
    {
      key: '3',
      tab: '已完成',
      type: 'finished_count'
    },
    {
      key: '-1',
      tab: '拒绝提现',
      type: 'reject_count'
    }
  ])

  // 详情弹窗
  const [isModalOpen, setIsModalOpen] = useState(false)

  // 当前详情信息
  const [currentDetailsObj, setCurrentDetailsObj] = useState({})

  // 处理 tab 切换
  const handleTabActive = key => {
    setTabActiveKey(key)
    tableRef.current.reload()
  }

  //  合并数量进tab徽标
  const formatTabs = tabsItem => {
    // eslint-disable-next-line guard-for-in
    setTabList(
      tabList.map(i => ({
        key: i.key,
        tab: (
          <Badge
            key={i.key}
            count={tabsItem[i.type]}
            overflowCount={99999}
            status='error'
            style={{
              position: 'relative',
              top: '5px',
              margin: '5px',
              padding: '3px 8px',
              boxSizing: 'border-box',
              borderRadius: '15px',
              fontSize: '14px'
            }}
          >
            <span>{i.tab}</span>
          </Badge>
        )
      }))
    )
  }

  // 查看详情
  const handleCheckDetail = (currentObj, record) => {
    setCurrentDetailsObj({
      ...currentObj,
      ...record
    })
    setIsModalOpen(true)
  }

  const searchColumns = [
    {
      title: '提现方式',
      dataIndex: 'withdraw_type',
      hideInTable: true,
      valueType: 'select',
      valueEnum: methodList
    },
    {
      title: '交易流水号',
      dataIndex: 'out_trade_no',
      hideInTable: true
    },
    {
      title: '申请时间',
      hideInTable: true,
      valueType: 'dateTimeRange',
      search: {
        transform: value => {
          return {
            apply_time_start: value[0],
            apply_time_end: value[1]
          }
        }
      }
    },
    {
      title: '收款账户',
      dataIndex: 'collection_account',
      hideInTable: true
    },
    {
      title: '收款人姓名',
      dataIndex: 'collection_name',
      hideInTable: true
    }
  ]

  const originColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '提现方式',
      dataIndex: 'withdraw_type_desc',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '提现金额',
      dataIndex: 'withdraw_amount',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '交易流水号',
      dataIndex: 'out_trade_no',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '收款账户',
      dataIndex: 'collection_account',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '收款人姓名',
      dataIndex: 'collection_name',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        const { status } = record
        let currentObj = {}
        if (status) {
          currentObj = STATUS_OBJ[status.toString()]
        }
        return (
          <>
            {
              <div className='settlement_status'>
                <div className='settlement_status_top'>
                  <Badge status={currentObj.statusType} />
                  <span>{currentObj.status}</span>
                </div>
                {currentObj.btnText && (
                  <Button
                    size='small'
                    type='primary'
                    onClick={() => handleCheckDetail(currentObj, record)}
                    style={{ background: currentObj.btnColor }}
                  >
                    {currentObj.btnText}
                  </Button>
                )}
              </div>
            }
          </>
        )
      }
    },
    {
      title: '申请时间',
      dataIndex: 'apply_time',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '处理人',
      dataIndex: 'op_name',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '处理备注',
      dataIndex: 'remarks',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '处理时间',
      dataIndex: 'op_time',
      align: 'center',
      hideInSearch: true
    },
    ...searchColumns
  ]

  const goApply = () => {
    history.push('/withdrawalApply')
  }

  return (
    <div className='withdraw_record_wrapper'>
      <div className='withdraw_record_title'>
        <h3 className='title'>提现记录</h3>
        <Button icon={<TransactionOutlined />} type='primary' onClick={goApply}>
          我要提现
        </Button>
      </div>
      <Alert
        className={'alert_money_box'}
        message={
          <Space>
            <div className='alert_money'>
              <div>
                可提现金额: <span>{amountList.total_surplus_withdraw_amount}元</span>
              </div>
              <div>
                已提现总和: <span>{amountList.total_withdrawn_amount}元</span>
              </div>
              <div>
                提现冻结中: <span>{amountList.total_withdraw_freeze_amount}元</span>
              </div>
              <div>
                总计: <span>{amountList.total_order_deal_amount}元</span>
              </div>
            </div>
          </Space>
        }
        type='info'
        showIcon
        banner
      />
      <ProTable
        actionRef={tableRef}
        request={async params => {
          const param = {
            ...params,
            page: params.current,
            per_page: params.pageSize,
            type: tabActiveKey
          }

          setCurrentPage(params.current)
          setPageSize(params.pageSize)
          const res = await GetPartnerWithdrawList(param)
          const { list, mark_stat, top_stat } = res
          const { total, data } = list

          formatTabs(mark_stat)
          setAmountList(top_stat)

          return {
            data,
            success: true,
            total
          }
        }}
        pagination={{
          pageSize: pageSize,
          current: currentPage
        }}
        rowKey='id'
        scroll={{ x: 'max-content' }}
        columns={originColumns}
        search={{
          defaultCollapsed: false,
          labelWidth: 80,
          span: 8
        }}
        toolbar={{
          multipleLine: true,
          tabs: {
            onChange: key => handleTabActive(key),
            activeKey: tabActiveKey,
            items: tabList
          }
        }}
        summary={pageData => {
          return (
            <>
              <Table.Summary.Row style={{ background: '#F9FBFC' }}>
                {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(item => {
                  return (
                    <Table.Summary.Cell key={item} index={item}>
                      {amountList && (
                        <div className='summary_box'>
                          {item === 0 ? '条件统计' : item === 2 ? amountList.bottom_cond_stat : '-'}
                        </div>
                      )}
                    </Table.Summary.Cell>
                  )
                })}
              </Table.Summary.Row>
            </>
          )
        }}
      />
      <WithdrawalRecordDetails
        setIsModalOpen={setIsModalOpen}
        isModalOpen={isModalOpen}
        currentDetailsObj={currentDetailsObj}
        tableRef={tableRef}
      />
    </div>
  )
}
